<?php

namespace common\models;

use Yii;

/**
 * 尽调报告-干系人及资产涉诉情况
 * This is the model class for table "project_investigation_lawsuit".
 *
 * @property string $id
 * @property string $project_id
 * @property string $records_number
 * @property string $accuser
 * @property string $defendant
 * @property string $money
 * @property string $court
 * @property string $lawsuit_content
 * @property string $created_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 * @property string $stakeholder_id
 */
class ProjectInvestigationLawsuit extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_investigation_lawsuit';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['project_id', 'stakeholder_id'], 'required'],
            [['project_id', 'lock_user', 'stakeholder_id'], 'integer'],
            [['lawsuit_content'], 'string'],
            [['created_at'], 'safe'],
            [['records_number', 'accuser', 'defendant', 'money', 'court', 'lock_timestamp'], 'trim'],
            [['records_number', 'accuser', 'defendant', 'money', 'court', 'lock_timestamp'], 'string', 'max' => 255],
            //['money', 'validateMoney'],
        ];
    }

    public function validateMoney()
    {
        if (!is_numeric($this->money)) {
            $this->addError('money', '涉诉金额必须是数值。');
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目',
            'records_number' => '案号',
            'accuser' => '原告',
            'defendant' => '被告',
            'money' => '涉诉金额',
            'court' => '法院',
            'lawsuit_content' => '涉诉内容',
            'created_at' => '创建时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
            'stakeholder_id' => '干系人及资产信息',
        ];
    }

    /**
     * 获取列表
     * @param $where
     * @return array
     */
    public function getList($where)
    {
        $list = (new yii\db\Query())
            ->select([])
            ->from($this->tableName())
            ->where($where)
            ->orderBy(['id' => SORT_ASC])
            //->indexBy('id')
            ->all();
        return $list;
    }


    /**
     * @param $id 主键
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * @param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $project_id, $changedAttributes, $userId, $module/*, $module_type*/, $type)
    {
        $model = self::findOne((int)$id);
        $project = Project::findOne($project_id);
        $stakeholder = ProjectInvestigationStakeholder::findOne($model->stakeholder_id);
        if ($model === null || $project === null || $stakeholder === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        if ($project->type != 2) {
            $project->type = 1;
        }

        switch ($stakeholder->stakeholder_type) {
            case 1:
                //$str = '【干系人类型：借款人】';
                $str = '【借款人】';
                break;
            case 2:
                //$str = '【干系人类型：抵押人】';
                $str = '【抵押人】';
                break;
            case 3:
                //$str = '【干系人类型：保证人】';
                $str = '【保证人】';
                break;
            case 4:
                //$str = '【干系人类型：其他承债人】';
                $str = '【其他承债人】';
                break;
            default:
        }

        $attributeLabels = $this->attributeLabels();
        $intAttributeLabels = ['project_id', 'lock_user', 'stakeholder_id'];
        $userInfo = (new UserModel())->getDepartmentUsersList();

        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增' . $str;
                    foreach ($data as $key => $value) {
                        if ($value != '') {
                            if (in_array($key, $intAttributeLabels)) {
                                switch ($key) {
                                    case 'project_id':
                                        $value = $project->title;
                                        break;
                                    case 'lock_user':
                                        if ($value > 0) {
                                            $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                        }
                                        break;
                                    case 'stakeholder_id':
                                        $value = $stakeholder->stakeholder_title;
                                    default:
                                }
                            }
                            if ($attributeLabels[$key] != 'ID') {
                                $log .= "{$attributeLabels[$key]}：{$value}\n";
                            }
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {

//                    $model->lock_user = null;
//                    $model->lock_timestamp = null;
//                    if ($model->save()) {
//                        return array('state' => true, 'msg' => '保存成功');
//                    } else {
//                        return array('state' => false, 'msg' => '保存失败');
//                    }

                    return array('state' => true, 'msg' => '保存成功');
                    //return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '' . $str;
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                case 'lock_user':
                                    if ($value > 0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除" . $str . "记录，";
                break;
            default:
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            if ($project->type != 2) {
                $project->type = 1;
            }
            $module_title_array = $projectUpdateLog->getModuleArrayTitle($project->type);
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            $projectUpdateLog->type = $project->type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new \Exception('添加涉诉操作日志失败');
            }

            return array('state' => true, 'msg' => '添加涉诉操作日志成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
